package com.carlinfo.shop.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringEscapeUtils;

/**
 * http的工具类
 * @author wangshMac
 */
public class HttpUtil
{
	/**
	 * ~主流程
	 * 
	 * http请求有三个要素:和当年的ajax,当年的写信很像;
	 * 	URL:
	 * 	信的内容(参数):?键=值&键=值
	 * 	返回值:(回信)
	 * 
	 * IO流:
	 */
	public String methodGet(String requestUrl , Map<String, String> headerMap,Map<String, String> paramsMap)
	{
		StringBuffer sb = new StringBuffer() ; 
		System.out.println("==methodGet==");
		try
		{
			/*
			 * 第一个参数必须是?
			 * */
			if(requestUrl.indexOf("?") == -1)
			{
				requestUrl = requestUrl + "?" ; 
			}
			/* 拼装url参数 */
			for (Iterator iterator = paramsMap.entrySet().iterator(); iterator.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				String key = me.getKey() + "" ; 
				String val = me.getValue() + ""; 
				
				requestUrl = requestUrl + "&" + key + "=" + val  ;
			}
			System.out.println("==requestUrl=>" + requestUrl);
			/* 创建一个url对象;
			 * url:
			 * http://www.baidu.com/s?id=1&a=2&b=3
			 * 协议://ip(域名):端口/文件的位置?参数
			 *  */
			URL url = new URL(requestUrl) ;
			/* 打开一个链接 
			 * 返回值=右边是父类,
			 * =左边是子类,需要强转
			 * ClassCaseExecption:
			 * instanceof
			 * */
			HttpURLConnection connection = (HttpURLConnection) url.openConnection() ;
			/* 拼装请求头 */
			for (Iterator iterator = headerMap.entrySet().iterator(); iterator.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				String key = me.getKey() + "" ; 
				String value = me.getValue() + "" ; 
				connection.setRequestProperty(key, value);
			}
			
			/* 开水管 */
			InputStream is = connection.getInputStream() ; 
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
			
			String line = "" ; 
			while((line = br.readLine()) != null)
			{
				//System.out.println("---->" + line);
				sb.append(line);
			}
		} catch (MalformedURLException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		} 
		return sb.toString() ; 
	}
	
	/**
	 * 专门来模拟post请求
	 * @param requestUrl	收信人
	 * @param headerMap		信封的内容
	 * @param paramsMap		信的内容
	 * @return
	 */
	public String methodPost(String requestUrl,Map<String, String> headerMap,Map<String, String> paramsMap)
	{
		StringBuffer sb = new StringBuffer() ; 
		try
		{
			/* 声明一个url */
			URL url = new URL(requestUrl);
			/* connection:链接;jdbc:java data base connection */
			HttpURLConnection connection = (HttpURLConnection) url.openConnection() ; 
			
			/* 如果是post,必须设置为doinput,doouput=true */
			connection.setDoOutput(true);
			
			/* 信封 */
			for (Iterator iterator = headerMap.entrySet().iterator(); iterator.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				connection.setRequestProperty(me.getKey() + "", me.getValue() + "");
			}
			/* 信的内容
			 * 	不管是post还是get
			 * 信的内容都是键=值&键=值
			 *  */
			String content = "" ; 
			for (Iterator iterator = paramsMap.entrySet().iterator(); iterator.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				String key = me.getKey() + ""; 
				String value = me.getValue() + "" ; 
				content = content + key + "=" + me.getValue() + "&";
			}
			System.out.println("====>" + content);
			/* 把信的内容放到信封里面
			 * get:直接放到url后面?开头就可以
			 * post:要把此内容放到请求体里面
			 *  */
			OutputStream os = connection.getOutputStream() ; 
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
			/* 将信放到邮局中 */
			bw.write(content);
			bw.flush();
			bw.close();
			
			/* 回信的信封 */
			System.out.println("==getResponseCode==>" + connection.getResponseCode());
			System.out.println("==getResponseMessage==>" + connection.getResponseMessage());
			/* 读取服务器的内容
			 * 回信的内容
			 *  */
			InputStream is = null;
			/* 如果报错,就要从错误流中取值 */
			if(connection.getResponseCode() != 200)
			{
				is = connection.getErrorStream();
			}else
			{
				is = connection.getInputStream() ;
			}
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			
			String line = "" ;
			while((line = br.readLine()) != null)
			{
				sb.append(line);
			}
			
			br.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		} 
		return sb.toString() ; 
	}
	
	public static void main(String[] args)
	{
		HttpUtil httpUtil = new HttpUtil() ; 
		String url = "https://weibo.com/a/aj/transform/loadingmoreunlogin?ajwvr=6&category=0&page=3&lefnav=0&__rnd=1522219023936"; 
		/* 参数 */
		Map<String, String> paramsMap = new HashMap<String,String>();
		/*paramsMap.put("a", "10");
		paramsMap.put("b", "20");
		paramsMap.put("c", "30");*/
		/* 请求头Map
		 * 主要是完全模块浏览器发出的请求 */
		Map<String, String> headerMap = new HashMap<String,String>();
		headerMap.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0");
		String result = httpUtil.methodGet(url, headerMap,paramsMap);
		/*String result = httpUtil.methodPost(url, headerMap,paramsMap);*/
		System.out.println("====" + result);
		/* 将\ u(unicode码转换成中文) 需要引入:commons-lang3包*/
		result = StringEscapeUtils.unescapeJava(result);
		System.out.println("====" + result);
	}
	
	public static void main_self(String[] args)
	{
		HttpUtil httpUtil = new HttpUtil() ; 
		String url = "http://localhost:10001/shop-web-head/spideradsfasfd_server.jsp"; 
		/* 参数 */
		Map<String, String> paramsMap = new HashMap<String,String>();
		paramsMap.put("a", "10");
		paramsMap.put("b", "20");
		paramsMap.put("c", "30");
		/* 请求头Map
		 * 主要是完全模块浏览器发出的请求 */
		Map<String, String> headerMap = new HashMap<String,String>();
		headerMap.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0");
		/*String result = httpUtil.methodGet(url, headerMap,paramsMap);*/
		String result = httpUtil.methodPost(url, headerMap,paramsMap);
		System.out.println("====" + result);
	}
}
